<template>
    <div class="compressorContent">
      <el-card>
        <el-page-header @back="router.back()">
          <template #content>
            <span class="text-large font-600 mr-3" style="color: #fff;"> {{ route.query.title }} </span>
          </template>
        </el-page-header>
      </el-card>
      <div class="compressorMain">
        <el-card style="background: black;">
          <div class="content">
            <div class="left">
              <el-form label-width="100px">
                <el-form-item label="图片地址：" prop="content">
                  <el-input show-word-limit v-model="compressorBefore" placeholder="手动输入图片地址" maxlength="1024" style="width: 90%;height: 40px;" :disabled="imgFile != ''" />
                </el-form-item>
                <el-form-item label="所选图片：" prop="content" style="margin-top: 20px;">
                  <div class="imgDefault" v-if="!imgFile" @click.stop="imgMessage">
                    <el-icon style="width: 100%;height: 100%;color: rgba(238, 238, 238, 0.8);font-weight: 100;font-size: 70px;">
                      <Plus style="border: none;" />
                    </el-icon>
                  </div>
                  <img :src="`data:image/png;base64,${imgFile}`" style="width: 90%;height: auto;" alt="" v-else>
                </el-form-item>
                <el-form-item
                  :prop="imgFile"
                  style="margin-top: 5px;"
                >
                  <el-upload
                    ref="upload"
                    action="#"
                    :http-request="PTuploadHttpRequest"
                    :show-file-list="false"
                    class="upload-demo"
                    multiple
                    :limit="1"
                    :on-exceed="PThandleExceed"
                  >
                    <el-button icon="CameraFilled" class="upload-demo-btn" type="primary">{{ imgFile == '' ? '点此选择图片' : '点此重新上传' }}</el-button>
                  </el-upload>
                </el-form-item>
                <el-form-item style="width: 92%;margin-top: 50px;display: flex;">
                  <el-button type="primary" style="flex: 1;height: 50px;border-radius: 8px;font-size: 16px;" @click="onturn">
                    开始压缩
                  </el-button>
                  <el-button type="danger" style="width: 150px;height: 50px;border-radius: 8px;font-size: 16px;" @click="clean">
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            <div class="right">
              <el-form>
                <el-form-item label="" prop="content" label-width="5px">
                    <div v-if="compressorAfter">
                        <img style="width: 100%;height: auto;" :src="compressorAfter" alt="">
                        <p style="font-size: 16px;font-weight: 600;">压缩信息: </p>
                        <p>压缩前为：<span style="color: greenyellow;">{{ sizeBefore }}KB</span></p>
                        <p>压缩后为：<span style="color: greenyellow;">{{ sizeAfter }}KB</span></p>
                        <p>对比之前压缩了：<span style="color: greenyellow;">{{ sizeValue }}KB</span></p>
                    </div>
                    <div style="width: 100%;height: 400px;background-color: azure;display: flex;justify-content: center;align-items: center;" v-else>
                        <span style="color: rgba(248,216,82);font-size: 40px;font-weight: 600;">请上传后压缩</span>
                    </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { UploadProps, UploadRawFile } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue';
  import { getBase64, useCompressor } from '@/utils/plugins'
  
  
  const route = useRoute()
  const router = useRouter()
  
  const compressorBefore = ref<string>('')
  const imgFile = ref<any>('')
  const compressorAfter = ref<string>('')
  const compressorFile = ref<any>('')
  const sizeBefore = ref<string>('')
  const sizeAfter = ref<string>('')

  const sizeValue = computed(() => {
    const result = ((Number(sizeBefore.value) - Number(sizeAfter.value)).toFixed(2)).toString() || '失败'
    return result
  })

  const onturn = () => {
    if (compressorBefore.value == '' && imgFile.value == '') {
      ElMessage({
        type: 'warning',
        message: '请选择图片或输入图片地址！'
      })
    } else {
      ElMessageBox.confirm('确定要开始压缩吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      showClose: false,
      closeOnClickModal: false,
    })
      .then(() => {
        window.showGlobalLoading()
        // recognize 第一个参数：图像，第二个：语种
        // const url = 'https://tesseract.projectnaptha.com/img/eng_bw.png'
        let url
        if (compressorBefore.value) {
          url = compressorBefore.value
        } else {
          url = `data:image/png;base64,${imgFile.value}`
        }
        console.log('url', url)
        const _imgFile = compressorFile.value
        useCompressor(_imgFile).then((_imgFile: any) => {
            const formData = new FormData()
            formData.append('file', _imgFile)
            formData.append('type', 'freight')
            console.log('_imgFile', _imgFile)
            sizeAfter.value = ((_imgFile.size / 1024).toFixed(2)).toString()
            getBase64(_imgFile).then((res: any) => {
                const img_url = res.split(',')[1]
                compressorAfter.value = `data:image/png;base64,${img_url}`
                window.hideGlobalLoading()
                console.log('compressorAfter.value', compressorAfter.value)
            })
        })
      })
    }
  }  
  const clean = () => {
    compressorBefore.value = ''
    imgFile.value = ''
    compressorAfter.value = ''
  }
  
  const imgMessage = () => {
    ElMessage({
      type: 'warning',
      message: '该区域仅为展示区域，上传图片请点击下方按钮操作！'
    })
  }
  
  // 首次上传
  const PTuploadHttpRequest = (data: any) => {
    if (compressorBefore.value != '') {
      ElMessage.warning('手动输入后无需上传文件！')
      return
    }
    console.log('data', data)
    if (data.file.type !== 'image/png' && data.file.type !== 'image/jpeg') {
      imgFile.value == ''
      ElMessage.error('请选择格式为jpg或者png类型的图片文件')
      return
    }
    clean()
    compressorFile.value = data.file
    sizeBefore.value = ((compressorFile.value.size / 1024).toFixed(2)).toString()
    getBase64(data.file).then((res: any) => {
      imgFile.value = data.file.name
      const img_url = res.split(',')[1]
      imgFile.value = img_url
      console.log('imgFile.value', imgFile.value)
    })
  }
  
  // 重复上传
  const PThandleExceed: UploadProps['onExceed'] = (files: any) => {
    if (compressorBefore.value != '') {
      ElMessage.warning('手动输入后无需上传文件！')
      return
    }
    const file = files[0] as UploadRawFile
    console.log('file', file)
    if (file.type !== 'image/png' && file.type !== 'image/jpeg') {
      imgFile.value == ''
      ElMessage.error('请选择格式为jpg或者png类型的图片文件')
      return
    }
    clean()
    compressorFile.value = file
    sizeBefore.value = ((compressorFile.value.size / 1024).toFixed(2)).toString()
    getBase64(file).then((res: any) => {
      imgFile.value = file.name
      const img_url = res.split(',')[1]
      imgFile.value = img_url
      console.log('form.value.ios_ptFile', imgFile.value)
    })
  }
  
  onMounted(() => {
  
  })
  
  </script>
  
  <style lang="scss" scoped>
  .compressorContent {
    width: 100%;
  
    .el-card {
      border-radius: $base-card-border-radius;
    }
  
    .compressorMain {
      margin-top: 20px;
      padding: 20px;
  
      .el-card {
        border-radius: 16px;
        box-shadow: 0px 4px 18px 0px rgba(248,216,82, 0.9);
  
        .content {
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: row;
  
          .left {
            flex: 1.5;
            padding: 10px;
            padding-left: 20px;
            
            .imgDefault {
              width: 90%;
              height: 200px;
              border: 1px dashed #eeeeee;
              display: flex;
              justify-content: center;
              align-items: center;
              cursor: pointer;
            }
            .imgDefault :hover {
                border: 1px dashed rgba(248,216,82, 0.9);;
                color: rgba(248,216,82, 0.9);
              }
            .upload-demo {
              display: block;
              width: 90%;
              height: 55px;
              line-height: 55px;
              text-align: center;
              font-size: 14px;
              background: rgb(248,216,82);
              color: white;
              border-radius: 5px;
            }
            .upload-demo-btn {
              width: 90%;
              height: 55px;
              line-height: 55px;
              background: rgb(248,216,82);
              border: rgb(248,216,82);
              color: #c57c43;
              text-align: center;
              font-size: 18px;
              border-radius: 5px;
            }
            
          }
  
          .right {
            flex: 1;
            padding: 10px;
            padding-right: 20px;
  
            :deep(.el-textarea__inner) {
              width: 100%;
              height: 55vh;
              border-radius: 8px;
            }
          }
        }
      }
    }
  
  }
  </style>